import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// const zhData = require('./lang/ZH.js');
import config from './config.js';
const scanPath = config.scanPath;


/**
 * @description 得到所有文件
 */


const fileDisplay =async (filePath,callback)=> { //遍历所有文件
	let keyMaps = fs.readFileSync(path.resolve('./dist/.translation_temp.json'),'utf-8');
	keyMaps = JSON.parse(keyMaps);
	//根据文件路径读取文件，返回文件列表
  let files =  fs.readdirSync(filePath)
	//遍历读取到的文件列表
	let md5s = fs.readFileSync(path.resolve('./dist/.file_md5.json'),'utf-8');
	md5s = JSON.parse(md5s);
	for (let index = 0; index < files.length; index++) {
		const filename = files[index];
		//获取当前文件的绝对路径
		let filedir = path.join(filePath, filename);
		let stats = fs.statSync(filedir)
		if(stats){
			let isFile = stats.isFile(); //是文件
			let isDir = stats.isDirectory(); //是文件夹
			if (isFile) {
				if(path.extname(filedir)!='.vue') return;
				let doc = fs.readFileSync(filedir,'utf-8')
				for(let key in keyMaps){
					doc = doc.replace(key,keyMaps[key])
				}

				const regex = /<script\b[^>]*>/gi;
				let scriptMatch,script;
				while ((scriptMatch = regex.exec(doc)) !== null) {
					script = scriptMatch[0];
				}
				let preScriptIndex =  doc.lastIndexOf(script) + script.length
				let preScript = doc.slice(0,preScriptIndex)
				let nextScript = doc.slice(preScriptIndex)
				let fileId = ''
				Object.keys(md5s).forEach(key=>{
					console.log(key,filedir);

					if(filedir.indexOf(key) > -1){
						fileId = md5s[key]
					}
				})
				doc = preScript
				 + `\n  //@i18n-file-id: ${fileId}`
				 + `\n  import { useI18n } from 'vue-i18n'`
				 + `\n  const { t } = useI18n()`
				 + nextScript
				fs.writeFile(filedir, doc, err => {
						if (err) throw err
						console.log(filedir+'多语言替换完毕，文件已被写入')
				})
				// console.log(scripts)

			}
			if (isDir) {
				fileDisplay(filedir); //递归，如果是文件夹，就继续遍历该文件夹下面的文件
			}
		}

	}
	callback&&callback.call()
}

//扫描目录得到所有中文文件
fileDisplay(scanPath);